﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using IronCow;
using Milkify.Interfaces;
using Milkify.Data;

namespace Milkify
{
    public class ApplicationExceptionHandler
    {
        private IViewFactory mViewFactory;
        private IViewContainer mViewContainer;

        public ApplicationExceptionHandler(IViewFactory viewFactory, IViewContainer viewContainer)
        {
            mViewFactory = viewFactory;
            mViewContainer = viewContainer;

            if (!System.Diagnostics.Debugger.IsAttached)
            {
                if (Application.Current != null)
                    Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            }
        }

        public void HandleException(Exception e)
        {
            if (e is TargetInvocationException)
                e = e.InnerException;
            if (mViewContainer == null)
                return;
            if (mViewContainer.CurrentView.GetName() != "Error")
            {
                var view = mViewFactory.Create("Error");

                ErrorViewData viewData;
                if (e is RtmException)
                {
                    viewData = new ErrorViewData("Problem Communicating With RTM", ((RtmException)e).ResponseError.ToString() + ": " + e.Message, e);
                }
                else if (e is IronCowException)
                {
                    viewData = new ErrorViewData("Problem Handling RTM Data", e);
                }
                else
                {
                    viewData = new ErrorViewData(e);
                }

                view.ViewData = viewData;
                mViewContainer.NavigateToView(view);
            }
        }

        private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            HandleException(e.Exception);
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show("A critical error is forcing Milkify to shut down.");
        }
    }
}
